import Vue from 'vue'
import Router from 'vue-router'

// 正常加载
// import Home from '../views/home'
// import About from '../views/About'


// 按需（懒）加载
function loadView (view, folder3, folder2, folder1) {
    if (folder1) {
        return () => import(/* webpackChunkName: "view-[request]" */ `@/views/${folder1}/${folder2}/${folder3}/${view}.vue`)
    } else if (folder2) {
        return () => import(/* webpackChunkName: "view-[request]" */ `@/views/${folder2}/${folder3}/${view}.vue`)
    } else if (folder3) {
        return () => import(/* webpackChunkName: "view-[request]" */ `@/views/${folder3}/${view}.vue`)
    } else {
        return () => import(/* webpackChunkName: "view-[request]" */ `@/views/${view}.vue`)
    }
}


const routerView = `<transition name="fade-transform" mode="out-in"><router-view></router-view></transition>`;


Vue.use(Router)

let base = `${process.env.BASE_URL}` // 动态获取二级目录

const router = new Router({
    mode: 'history', // 路由有两种模式：history、hash，想要不带#号就选history，默认是hash模式
    base: base,
    routes: [
        {
            path: '/login',
            name: 'login',
            hidden: true,
            component: loadView('index', 'login')
        },

    ],
    scrollBehavior (to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            return {
                x: 0,
                y: 0
            }
        }
    }
});

import store from "@/store"
import asyncRoutesFn from "./asyncRoutes.js"
router.beforeEach(async (to, from, next) => {
    const isLogin = store.state.user.userInfo ? true : false
    console.log(store.state.user);
    if (!isLogin && to.name !== 'login') {
        router.push({ name: 'login' })
        next()
    } else {
        if (router.options.routes.length === 1 && to.name != "login") {
            await store.dispatch('user/getJurisdiction')
            let asyncRoutes = asyncRoutesFn(store.state.user.authorityList)
            if (asyncRoutes[0]) {
                router.addRoutes(asyncRoutes)
                router.options.routes = [...asyncRoutes, ...router.options.routes]
                return next({ ...to, replace: true })
            }
        }
        next()
    }
});

const routerPush = Router.prototype.push
Router.prototype.push = function push (location) {
    return routerPush.call(this, location).catch(error => error)
}


export default router;

